Page({
    data: {
      goodsId: null,
      goodsInfo: null,
      address: '',
      currentDate: new Date(),
      selectedDate: '',
      selectedTime: '',
      selectedDuration: '2小时',
      remark: '',
      phone: '',
      durations: ['2小时', '3小时', '4小时', '5小时', '6小时'],
      calendar: {
        selectedYear: new Date().getFullYear(),
        selectedMonth: new Date().getMonth() + 1,
        days: [],
        weekDays: ['日', '一', '二', '三', '四', '五', '六']
      },
      userId: null, // 用户ID
      userPhone: '', // 用户电话
      defaultAddress: {
        name: '臭杆子',
        phone: '15630352072',
        address: '河北省保定市万博广场'
      },
      timeSlots: [
        '9:00', '9:30', '10:00', '10:30',
        '11:00', '11:30', '12:00', '14:00',
        '14:30', '15:00', '15:30', '16:00',
        '16:30', '17:00'
      ],
      orderId: null,
      isEditMode: false
    },
  
    onLoad: function(options) {
      console.log('预约页面接收到的参数:', options);
      
      if (options.orderId) {
        // 编辑订单预约时间场景
        this.setData({
          orderId: options.orderId,
          isEditMode: true
        });
        
        // 加载订单信息
        this.loadOrderInfo(options.orderId);
      } 
      else if (options.goodsId) {
        // 新建订单场景
        const goodsId = options.goodsId;
        // 使用假数据
        const goodsInfo = {
          'KF174194004243589': {
            id: 7,
            gid: 'KF174194004243589',
            gname: '日常保洁',
            price: 300.00,
            sales: 1000,
            prove: '/static/images/cleaning1.png'
          },
          'KF174194004243587': {
            id: 8,
            gid: 'KF174194004243587',
            gname: '深度保洁',
            price: 300.00,
            sales: 800,
            prove: '/static/images/cleaning2.png'
          },
          'KF174194004243588': {
            id: 9,
            gid: 'KF174194004243588',
            gname: '除螨服务',
            price: 300.00,
            sales: 600,
            prove: '/static/images/cleaning3.png'
          }
        };

        this.setData({
          goodsId: goodsId,
          goodsInfo: goodsInfo[goodsId] || goodsInfo['KF174194004243589'],
          selectedDate: this.formatDate(new Date()),
          address: '河北省保定市万博广场',
          phone: '15630352072'
        });
      }

      // 设置默认用户ID和电话
      this.setData({
        userId: 1007,
        userPhone: '15630352072'
      });

      // 初始化日历
      this.initCalendar();
    },
  
    // 页面显示时重新加载地址
    onShow: function() {
      this.loadDefaultAddress()
    },
  
    // 初始化日历
    initCalendar: function() {
      const today = new Date();
      const year = today.getFullYear();
      const month = today.getMonth() + 1;
      const currentDate = today.getDate();
      
      const days = this.getDaysInMonth(year, month);
      const firstDay = new Date(year, month - 1, 1).getDay();
      
      const calendarDays = [];
      
      // 补充上个月的天数
      for (let i = 0; i < firstDay; i++) {
        calendarDays.push({
          day: '',
          disabled: true,
          selected: false
        });
      }
      
      // 添加本月天数
      for (let i = 1; i <= days; i++) {
        const date = new Date(year, month - 1, i);
        date.setHours(0, 0, 0, 0); // 设置时间为当天的0点
        const now = new Date();
        now.setHours(0, 0, 0, 0); // 设置当前时间为当天的0点

        calendarDays.push({
          day: i,
          isToday: i === currentDate,
          disabled: date < now, // 只禁用小于当前日期的日期
          selected: i === currentDate, // 默认选中当天
          date: `${year}-${String(month).padStart(2, '0')}-${String(i).padStart(2, '0')}`
        });
      }
      
      this.setData({
        'calendar.days': calendarDays,
        'calendar.selectedYear': year,
        'calendar.selectedMonth': month,
        selectedDate: this.formatDate(today)
      });
    },
  
    // 获取某月天数
    getDaysInMonth: function(year, month) {
      return new Date(year, month, 0).getDate()
    },
  
    // 加载默认地址
    loadDefaultAddress: function(userId) {
      if (!userId) return
      
      wx.request({
        url: 'http://localhost:9205/booking/selectByAddress',
        method: 'GET',
        data: {
          id: userId
        },
        success: (res) => {
          if (res.data) {
            this.setData({
              address: res.data
            })
          }
        }
      })
    },
  
    // 编辑地址
    editAddress: function() {
      wx.navigateTo({
        url: '/pages/ucenter/address/address'
      })
    },
  
    // 选择日期
    selectDate: function(e) {
      const index = e.currentTarget.dataset.index;
      const day = this.data.calendar.days[index];
      
      if (!day.day || day.disabled) return;
      
      // 更新所有日期的选中状态
      const updatedDays = this.data.calendar.days.map((d, i) => ({
        ...d,
        selected: i === index
      }));
      
      this.setData({
        'calendar.days': updatedDays,
        selectedDate: day.date
      });

      // 重置时间选择
      this.setData({
        selectedTime: ''
      });
    },
  
    // 判断时间是否可选
    isTimeDisabled: function(time) {
      const now = new Date();
      const today = this.formatDate(now);
      const selectedDate = this.data.selectedDate;
      const [hours, minutes] = time.split(':').map(Number);
      const currentHours = now.getHours();
      const currentMinutes = now.getMinutes();

      // 如果是今天
      if (selectedDate === today) {
        // 如果小时小于当前小时，禁用
        if (hours < currentHours) return true;
        // 如果小时等于当前小时，但分钟小于等于当前分钟，禁用
        if (hours === currentHours && minutes <= currentMinutes) return true;
      }

      return false;
    },
  
    // 选择时间
    selectTime: function(e) {
      const time = e.currentTarget.dataset.time;
      if (this.isTimeDisabled(time)) {
        wx.showToast({
          title: '不能选择过去的时间',
          icon: 'none'
        });
        return;
      }

      this.setData({
        selectedTime: time
      });
    },
  
    // 输入备注
    onRemarkInput: function(e) {
      this.setData({
        remark: e.detail.value
      })
    },
  
    // 选择时长
    onDurationChange: function(e) {
      this.setData({
        selectedDuration: this.data.durations[e.detail.value]
      });
    },
  
    // 提交预约
    submitBooking: function() {
      // 检查是否选择了时间
      if (!this.data.selectedDate || !this.data.selectedTime) {
        wx.showToast({
          title: '请选择预约时间',
          icon: 'none'
        });
        return;
      }

      // 检查选择的时间是否有效
      if (!this.isDateValid(this.data.selectedDate) || !this.isTimeValid(this.data.selectedTime)) {
        wx.showToast({
          title: '请选择有效的预约时间',
          icon: 'none'
        });
        return;
      }

      // 检查手机号格式
      if (!/^1[3-9]\d{9}$/.test(this.data.phone)) {
        wx.showToast({
          title: '请输入正确的11位手机号',
          icon: 'none'
        });
        return;
      }

      // 判断是修改订单日期还是新建订单
      if (this.data.isEditMode) {
        // 修改订单日期
        const dateTime = this.data.selectedDate + ' ' + this.data.selectedTime;
        
        wx.showLoading({
          title: '更新中...',
        });
        
        // 确保手机号和地址正确
        const phone = this.data.phone || '15630352072';
        const address = this.data.address || '河北省保定市万博广场';
        
        console.log('修改订单参数:', {
          date: dateTime,
          phone: phone,
          address: address,
          oid: this.data.orderId
        });
        
        // 调用后端接口更新订单日期
        wx.request({
          url: 'http://localhost:9205/order/updateByDate',
          method: 'GET',
          data: {
            date: dateTime,
            phone: phone,
            address: address,
            oid: this.data.orderId
          },
          success: (res) => {
            wx.hideLoading();
            console.log('更新订单响应:', res.data);
            wx.showToast({
              title: '预约信息已更新',
              icon: 'success'
            });
            
            // 返回上一页
            setTimeout(() => {
              wx.navigateBack();
            }, 1500);
          },
          fail: (err) => {
            wx.hideLoading();
            console.error('请求失败:', err);
            wx.showToast({
              title: '更新失败，请重试',
              icon: 'none'
            });
          }
        });
      } else {
        // 新建订单
        // 构造订单数据
        const orderData = {
          nid: 1007, // 使用固定的用户ID
          gid: this.data.goodsId.toString(),
          address: this.data.address,
          phone: this.data.phone,
          appointmentTime: this.data.selectedDate + ' ' + this.data.selectedTime,
          duration: this.data.selectedDuration
        };

        console.log('提交预约数据:', orderData);

        // 跳转到订单确认页
        wx.navigateTo({
          url: `/pages/services/homecare/confirm/index?orderData=${encodeURIComponent(JSON.stringify(orderData))}`
        });
      }
    },
  
    // 返回上一页
    goBack: function() {
      wx.navigateBack()
    },
  
    // 格式化日期
    formatDate: function(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
  
    // 选择日期
    onDateChange: function(e) {
      const selectedDate = e.detail.value;
      if (!this.isDateValid(selectedDate)) {
        wx.showToast({
          title: '不能选择过去的日期',
          icon: 'none'
        });
        return;
      }
      this.setData({
        selectedDate: selectedDate,
        selectedTime: '' // 重置时间选择
      });
    },
  
    // 输入地址
    onAddressInput: function(e) {
      this.setData({
        address: e.detail.value
      });
    },
  
    // 输入电话
    onPhoneInput: function(e) {
      this.setData({
        phone: e.detail.value
      });
    },
  
    // 检查日期是否可选
    isDateValid: function(dateStr) {
      const selectedDate = new Date(dateStr);
      const now = new Date();
      
      // 设置两个日期都为当天的0点，只比较日期
      selectedDate.setHours(0, 0, 0, 0);
      now.setHours(0, 0, 0, 0);
      
      return selectedDate >= now; // 当前日期及之后的日期都可选
    },
  
    // 检查时间是否可选
    isTimeValid: function(timeStr) {
      const now = new Date();
      const selectedDate = new Date(this.data.selectedDate);
      const [hours, minutes] = timeStr.split(':').map(Number);
      
      // 如果是今天
      if (this.formatDate(selectedDate) === this.formatDate(now)) {
        const currentHours = now.getHours();
        const currentMinutes = now.getMinutes();
        
        // 如果小时小于当前小时，或者小时相等但分钟小于等于当前分钟，则时间无效
        if (hours < currentHours || (hours === currentHours && minutes <= currentMinutes)) {
          return false;
        }
      }
      return true;
    },
  
    // 切换月份
    changeMonth: function(e) {
      const offset = parseInt(e.currentTarget.dataset.offset);
      const currentYear = this.data.calendar.selectedYear;
      let currentMonth = this.data.calendar.selectedMonth;
      
      currentMonth += offset;
      
      if (currentMonth > 12) {
        currentMonth = 1;
        currentYear++;
      } else if (currentMonth < 1) {
        currentMonth = 12;
        currentYear--;
      }
      
      const today = new Date();
      const days = this.getDaysInMonth(currentYear, currentMonth);
      const firstDay = new Date(currentYear, currentMonth - 1, 1).getDay();
      
      const calendarDays = [];
      
      // 补充上个月的天数
      for (let i = 0; i < firstDay; i++) {
        calendarDays.push({
          day: '',
          disabled: true,
          selected: false
        });
      }
      
      // 添加本月天数
      for (let i = 1; i <= days; i++) {
        const date = new Date(currentYear, currentMonth - 1, i);
        date.setHours(0, 0, 0, 0);
        const now = new Date();
        now.setHours(0, 0, 0, 0);

        // 如果是未来月份，所有日期都可选
        const isFutureMonth = currentYear > now.getFullYear() || 
                            (currentYear === now.getFullYear() && currentMonth > now.getMonth() + 1);
        
        calendarDays.push({
          day: i,
          isToday: date.getTime() === now.getTime(),
          disabled: !isFutureMonth && date < now, // 未来月份全部可选，当前月份只禁用过去的日期
          selected: false,
          date: `${currentYear}-${String(currentMonth).padStart(2, '0')}-${String(i).padStart(2, '0')}`
        });
      }
      
      this.setData({
        'calendar.days': calendarDays,
        'calendar.selectedYear': currentYear,
        'calendar.selectedMonth': currentMonth
      });
    },
  
    // 加载订单信息
    loadOrderInfo: function(orderId) {
      console.log('加载订单信息, orderId:', orderId);
      wx.request({
        url: `http://localhost:9205/order/getOrderById`,
        method: 'GET',
        data: {
          id: orderId
        },
        success: (res) => {
          console.log('获取订单详情响应:', res.data);
          if (res.data) {
            const orderInfo = res.data;
            
            // 如果有预约时间，分解成日期和时间
            let selectedDate = '';
            let selectedTime = '';
            
            if (orderInfo.date) {
              const dateParts = orderInfo.date.split(' ');
              selectedDate = dateParts[0];
              selectedTime = dateParts.length > 1 ? dateParts[1] : '';
            }
            
            // 确保地址和电话有值
            const address = orderInfo.address && orderInfo.address !== '暂无' 
                          ? orderInfo.address 
                          : '河北省保定市万博广场';
            const phone = orderInfo.phone && orderInfo.phone !== '暂无'
                        ? orderInfo.phone
                        : '15630352072';
            
            console.log('处理后的订单数据:', {
              goodsInfo: {
                gid: orderInfo.gid,
                gname: orderInfo.gname,
                price: orderInfo.price
              },
              address: address,
              phone: phone,
              selectedDate: selectedDate,
              selectedTime: selectedTime
            });
            
            this.setData({
              goodsInfo: {
                gid: orderInfo.gid,
                gname: orderInfo.gname || '家政服务',
                price: orderInfo.price || 300,
                prove: orderInfo.prove || '/static/images/cleaning1.png'
              },
              address: address,
              phone: phone,
              selectedDate: selectedDate,
              selectedTime: selectedTime,
              selectedDuration: orderInfo.duration || '2小时'
            });
            
            // 更新日历的选中日期
            this.updateCalendarSelection(selectedDate);
          } else {
            wx.showToast({
              title: '获取订单信息失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 更新日历的选中日期
    updateCalendarSelection: function(dateStr) {
      if (!dateStr) return;
      
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      
      this.setData({
        'calendar.selectedYear': year,
        'calendar.selectedMonth': month
      });
      
      // 重新初始化日历，以更新天数
      this.initCalendar();
      
      // 选中指定日期
      const days = this.data.calendar.days;
      for (let i = 0; i < days.length; i++) {
        if (days[i].day === day && !days[i].disabled) {
          days[i].selected = true;
          break;
        }
      }
      
      this.setData({
        'calendar.days': days
      });
    }
  })